{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dbb36581",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.ensemble import RandomForestRegressor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b33672de",
   "metadata": {},
   "outputs": [],
   "source": [
    "### 绘制缺失变量的热图\n",
    "def miss_heatamp(data,title):\n",
    "    cols = data.columns\n",
    "    colours = ['#006699', '#ffff99'] ## 第一项没缺失的颜色，第二项，缺失的颜色\n",
    "    \n",
    "    plt.figure(figsize=(12,8 ))\n",
    "    plt.rcParams['font.sans-serif'] = ['SimHei']  # 黑体\n",
    "    plt.rcParams['axes.unicode_minus'] = False    # 解决无法显示符号的问题\n",
    "    sns.set(font='SimHei', font_scale=1)\n",
    "    f = sns.heatmap(data[cols].isnull(), cmap=sns.color_palette(colours))\n",
    "    f.set_title(title)\n",
    "    \n",
    "miss_heatamp(filter_data,'变量热图')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e4ddd26",
   "metadata": {},
   "outputs": [],
   "source": [
    "##### 绘制缺失变量的直方图\n",
    "def miss_bar(data,title):\n",
    "    '''\n",
    "    data : dataframe格式的数据，行为数据，列为特征 \n",
    "    title : 图表名字\n",
    "    '''\n",
    "    missValue2miss_num={}\n",
    "    for col in data.columns:\n",
    "        missing = data[col].isnull()\n",
    "        num_missing = np.sum(missing)\n",
    "        if num_missing > 0:  \n",
    "            missValue2miss_num[col] = num_missing\n",
    "    df = pd.DataFrame([missValue2miss_num])\n",
    "    df.index=['miss_num']\n",
    "    df = df.T\n",
    "    \n",
    "    plt.figure(figsize=(10,8 ))\n",
    "    plt.rcParams['font.sans-serif'] = ['SimHei']  # 黑体\n",
    "    plt.rcParams['axes.unicode_minus'] = False    # 解决无法显示符号的问题\n",
    "    sns.set(font='SimHei', font_scale=1)\n",
    "\n",
    "    f = sns.barplot(x=df.index,y=df['miss_num'],color='#336699')\n",
    "    f.set_title(title)\n",
    "\n",
    "\n",
    "miss_bar(filter_data,'缺失值统计')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae59233e",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def rf_impute(data):\n",
    "    '''\n",
    "    data:dataframe格式\n",
    "    '''\n",
    "\n",
    "    copy_data = data.copy()\n",
    "    miss_columns = copy_data.isnull().sum()[copy_data.isnull().sum() != 0].sort_values().index.tolist() \n",
    "    unmiss_columns = copy_data.isnull().sum()[copy_data.isnull().sum() == 0].sort_values().index.tolist() \n",
    "    for col in miss_columns:\n",
    "        X_train = copy_data[copy_data[col].notnull()][unmiss_columns].values\n",
    "        Y_train = copy_data[copy_data[col].notnull()][col].values\n",
    "        X_test = copy_data[copy_data[col].isnull()][unmiss_columns][unmiss_columns].values\n",
    "        rfr=RandomForestRegressor()\n",
    "        rfr.fit(X_train,Y_train)\n",
    "        predict_value = rfr.predict(X_test)\n",
    "        copy_data.loc[(copy_data[col].isnull()),col] = predict_value\n",
    "        unmiss_columns.append(col)\n",
    "    return copy_data\n",
    "\n",
    "imp_data = rf_impute(filter_data)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
